package TeamR3.web;

import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import TeamR3.entity.MyJsonObject;
import TeamR3.entity.User;
import TeamR3.service.UserService;

@Controller
public class TeamR3_User_Controller {
	@Autowired
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@RequestMapping("/showAllUser.TeamR3")
	public @ResponseBody
	MyJsonObject queryAllUsers() {
		List<User> list = userService.queryAllUsers();
		if (list != null) {
			System.out.println("显示所有用户");
			for (User user : list) {
				System.out.println(user);
			}
			return new MyJsonObject(200, "显示所有用户", list);
		}else{
			System.out.println("数据库无数据或连接错误");
			return new MyJsonObject(201, "数据库无数据或连接错误");
		}
	}
	
	@RequestMapping(value = "/login.TeamR3" , method = RequestMethod.POST)
	public @ResponseBody MyJsonObject getUser(
			@RequestParam(value="user_name") String user_name,
			@RequestParam(value="user_password") String user_password){
		User resultUser = userService.getUser(user_name, user_password);
		System.out.println(resultUser);
		if(resultUser==null) return new MyJsonObject(201, "登陆失败");
		else return new MyJsonObject(200, "登陆成功", resultUser);
	}
	
	@RequestMapping("/addUser.TeamR3")
	public @ResponseBody MyJsonObject addUser(
			@RequestParam(value="user_name") String user_name,
			@RequestParam(value="user_password") String user_password,
			@RequestParam(value="user_privilege") int user_privilege){
		int affectedRow = userService.addUser(user_name, user_privilege, user_password);
		if(affectedRow==0){
			return new MyJsonObject(201, "添加失败");
		}else{
			return new MyJsonObject(200, "用户"+user_name +"添加成功", affectedRow);
		}
	}
	
	@RequestMapping("/modifyUser.TeamR3")
	public @ResponseBody MyJsonObject modifyUser(
			@RequestParam(value="user_name") String user_name,
			@RequestParam(value="user_password") String user_password,
			@RequestParam(value="user_privilege") int user_privilege){
		int affectedRow = userService.modifyUser(user_name, user_privilege, user_password);
		if(affectedRow==0){
			return new MyJsonObject(201, "修改失败");
		}else{
			return new MyJsonObject(200, "用户"+user_name +"修改成功", affectedRow);
		}
	}
	
	@RequestMapping("/delUser.TeamR3")
	public @ResponseBody MyJsonObject delUserUser(
			@RequestParam(value="user_name") String user_name){
		int affectedRow = userService.delUser(user_name);
		if(affectedRow==0){
			return new MyJsonObject(201, "删除失败");
		}else{
			return new MyJsonObject(200, "用户"+user_name +"删除成功", affectedRow);
		}
	}
}
